<?php
namespace App\Http\Controllers\Company;


use App\Exceptions\ApiException;
use App\Http\Requests\BasicRequest;
use App\Http\Requests\CompanyWorkCreateRequest;
use App\Models\ClientUser;
use App\Models\ClientUserIntegral;
use App\Models\ClientUserIntegralType;
use App\Models\ClientUserManagerWork;
use App\Models\ClientUserManagerDuty;
use App\Models\ClientUserManagerWorksImage;
use App\Models\ClientUserRoles;
use App\Models\HouseDistrict;
use App\Models\ManageMessage;
use App\Models\NeighborCouncilComplaints;
use App\Models\ClientUserWorking;
use App\Models\ServiceMonitor;
use Illuminate\Support\Facades\DB;

use App\Models\ClientUserRelationship;

class UsercenterController extends CommonController {
	
	public function index(BasicRequest $request){
		// 我的积分总数量(最新的积分数量)
		$integral = ClientUserIntegral::where(['uid'=>$this->uid])->latest()->value('integral_after') ?? 0;
		// 待处理投诉
		$complaints = NeighborCouncilComplaints::select(DB::raw('neighbor_council_complaints.id'))->leftJoin('client_user_house as h','h.uid','=','neighbor_council_complaints.uid')->where(['parent_id'=>0,'to_uid'=>$this->uid,'status'=>1])->where('h.uid','>',0)->groupBy('h.uid')->pluck('id')->count();
		// 值班时长
		$duty_time = ClientUserManagerDuty::where(['uid'=>$this->uid])->groupBy('uid')->where('end_time','>','0')->sum(DB::raw('end_time - start_time'));
		$duty_hour = round($duty_time / 3600,2);
		// 与业主聊天次数(每人看过的算一次)
		$count=DB::table('client_user_rongcloud_end')->where(['to_uid'=>$this->uid])->count('*');
		$is_monitor = ServiceMonitor::where(['village_id'=>$this->ship->village_id])->first();

		$data = [
			'user'		=> $this->user,
			'integral'	=> $integral,
			'duty_time'	=> $duty_hour,	// 值班时长
			'chat_count'=> $count,		// 接待次数（与业主聊天次数）
			'complaints'=> $complaints,
            'monitor'   => $is_monitor?1:0,

		];
		return json_success('OK',$data);
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 积分说明
	 */
	public function integral_type(BasicRequest $request){
		$type = ClientUserIntegralType::select('id','name','integral')->get();
		return json_success('OK',$type);
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 积分历史记录
	 */
	public function integral(BasicRequest $request){
		$integral = ClientUserIntegral::where(['uid'=>$this->uid])->latest()->value('integral_after') ?? 0;
		$history = ClientUserIntegral::where(['uid'=>$this->uid])->latest()->pages();
		$return = [
			'integral'	=> $integral,
			'history'	=> $history,
		];
		return json_success('OK',$return);
	}
	
	/**
	 * @param BasicRequest $request
	 * @throws ApiException
	 * @return array
	 * 管家——工作日志，时间筛选
	 */
	public function work(BasicRequest $request){
	     $uid =  $request->input('uid');
          if($uid) {
               $type = ClientUserRoles::where(['uid' => $uid])->value('type');
               if($type!=4){
                    $uid_in=  ClientUserRelationship::treeChildrenOne($uid,$type);
                    $uid=null;
               }else{
                    $uid_in = ClientUserRelationship::treeChildrenOne($this->ship->uid,$this->ship->type);
                    $uid_in->prepend(ClientUser::select(['id as uid', 'realname'])->find($this->uid));
                    $uid_in=$uid_in->pluck('uid');
               }
          }else{
               $uid_in = ClientUserRelationship::treeChildrenOne($this->ship->uid,$this->ship->type);
               $uid_in->prepend(ClientUser::select(['id as uid', 'realname'])->find($this->uid));
               $uid_in=$uid_in->pluck('uid');
          }
		$house_id = $request->input('house_id');
		$house = HouseDistrict::select(['id as house_id','name as name_long'])
             ->whereIn('id',explode(',',$this->ship->house_id))
             ->get()->each(function($v,$k){
                  $v->children = HouseDistrict::select(['id as house_id','name as name_long'])->whereIn('id',explode(',',$v->house_id))->get();
                   $v->children->prepend(['house_id'=>$v->house_id,'name_long'=>'全部']);
              });
		$house->prepend(['house_id'=>0,'name_long'=>'全部']);

		// 筛选类型，week/month
		$time_type = $request->input('time_type');
		// 之前时间个数，根据 time_type 不同而不同
		$time_before_count = $request->input('time_before_count',0);
		$start_time = '';
		$end_time = time2date();
		if($time_type == 'week'){
               $start_time = time2date(strtotime(date('Y-m-01 00:00:00')) + $time_before_count * 7 * 86400);
               $time_before_count_end = $time_before_count + 1;
               $end_time = time2date(strtotime(date('Y-m-01 00:00:00')) + $time_before_count_end * 7 * 86400);
		}elseif($time_type == 'month'){
			$start_time = date('Y-m-01 00:00:00',strtotime("-$time_before_count months"));
			$end_time =  date('Y-m-d 23:59:59',strtotime("$start_time +1 months -1 days"));
		}
//		dd($start_time,$end_time);
		$data = ClientUserManagerWork::select(DB::raw('client_user_manager_works.*,avatar,realname as username,mobile'))
		  ->whereIn('client_user_manager_works.uid',$uid_in)
          ->where('client_user_manager_works.type','=',0)
    		->when($start_time,function($query) use ($start_time){
    			$query->where('client_user_manager_works.created_at','>',$start_time);
    		})
          ->when($end_time,function($query) use ($end_time){
               $query ->where('client_user_manager_works.created_at','<=',$end_time);
          })
    	  ->when($house_id,function($query) use ($house_id){
    			$query->where(['client_user_manager_works.house_id'=>$house_id]);
    	  })->when($uid,function($query) use ($uid){
		     $query->where(['client_user_manager_works.uid'=>$uid]);
          })
		  ->orderBy('id','desc')
		  ->leftJoin('client_user as u','u.id','=','client_user_manager_works.uid')
		  //->groupBy('client_user_manager_works.work')
		  ->pages();
		
		$data->each(function($v){
			$images = $v->images()->pluck('image');
			$v->image = $images->first();
			$v->images = $images;
		});
		$time_week_pad = $time_month_pad = [];
          for ($i = 0; $i <5; $i++) {
               $time_week_pad[] = ['name' => date( 'Y年m月第'.($i+1) .'周'), 'value' => $i];
              
          }
		  for ($i = 0; $i <40; $i++) {
			   $time_month_pad[] = ['name' => date('Y年m月', strtotime("-$i months")), 'value' => $i];
		  }
		$time = [
			['name'=>'全部','value'=>'','children'=>[]],
			['name'=>'按周查看','value'=>'week','children'=> $time_week_pad],
			['name'=>'按月查看','value'=>'month','children'=> $time_month_pad],
		];
		$return = [
			'house'		=> $house,
			'time'		=> $time,
			'list'		=> $data,
		];
		return json_success('OK',$return);
	}
     /**
      * @param BasicRequest $request
      * @throws ApiException
      * @return array
      * 我的工作，时间筛选
      */
     public function my_work(BasicRequest $request){

          $house_id = $request->input('house_id');
          $house = HouseDistrict::select(['id as house_id','name as name_long'])
              ->whereIn('id',explode(',',$this->ship->house_id))
              ->get();
          $house->prepend(['house_id'=>0,'name_long'=>'全部']);

          // 筛选类型，week/month
          $time_type = $request->input('time_type');
          // 之前时间个数，根据 time_type 不同而不同
          $time_before_count = $request->input('time_before_count',0);
          $start_time = '';
          $end_time = time2date();
          if($time_type == 'week'){
               $start_time = time2date(strtotime(date('Y-m-01 00:00:00')) + $time_before_count * 7 * 86400);
               $time_before_count_end = $time_before_count + 1;
               $end_time = time2date(strtotime(date('Y-m-01 00:00:00')) + $time_before_count_end * 7 * 86400);
          }elseif($time_type == 'month'){
               $start_time = date('Y-m-01 00:00:00',strtotime("-$time_before_count months"));
               $end_time =  date('Y-m-d 23:59:59',strtotime("$start_time +1 months -1 days"));
          }
//		dd($start_time,$end_time);
          $data = ClientUserManagerWork::select(DB::raw('client_user_manager_works.*,avatar,realname as username,mobile'))
              ->where('client_user_manager_works.uid',$this->uid)
              ->when($start_time,function($query) use ($start_time,$end_time){
                   $query->where('client_user_manager_works.created_at','>',$start_time)->where('client_user_manager_works.created_at','<=',$end_time);
              })
              ->when($house_id,function($query) use ($house_id){
                   $query->where(['client_user_manager_works.house_id'=>$house_id]);
              })
              ->leftJoin('client_user as u','u.id','=','client_user_manager_works.uid')
			  ->orderBy('id','desc')
              //->groupBy('client_user_manager_works.work')
              ->pages();

          $data->each(function($v){
               $images = $v->images()->pluck('image');
               $v->image = $images->first();
               $v->images = $images;
          });
          $time_week_pad = $time_month_pad = [];
          for ($i = 0; $i <5; $i++) {
               $time_week_pad[] = ['name' => date( 'Y年m月第'.($i+1) .'周'), 'value' => $i];
               $time_month_pad[] = ['name' => date('Y年m月', strtotime("-$i months")), 'value' => $i];
          }
          $time = [
              ['name'=>'全部','value'=>'','children'=>[]],
              ['name'=>'按周查看','value'=>'week','children'=> $time_week_pad],
              ['name'=>'按月查看','value'=>'month','children'=> $time_month_pad],
          ];
          $return = [
              'house'		=> $house,
              'time'		=> $time,
              'list'		=> $data,
          ];
          return json_success('OK',$return);
     }
	// 添加工作日志
	public function work_create(CompanyWorkCreateRequest $request){		
		// 值班日志 check为1
		$check = ClientUserWorking::select('status','created_at','updated_at')->where(['uid'=>$this->uid,'status'=>1])->first();
        $status=$request->input('type');
		$work = $request->only(['work','unwork','work_help','work_remarks']);
		$work['uid'] = $this->uid;
		$work['created_at'] = time2date();
        $work['type'] = 0;
        $work['date'] = date('Y-m-d');
        if($status==1 && $check['status']==1){
           $insert = [];
           $insert['uid'] = $this->uid;
           $insert['start_time'] = $check['updated_at'] ? strtotime($check['updated_at']) : strtotime($check['created_at']);
           $insert['status'] = 1;
           $insert['created_at'] = time2date();
           $insert['date'] = date('Y-m-d');
           ClientUserManagerDuty::create($insert)->id;
           $work['type'] = 1;
        }
		// 处理上传的图片
		$images = json_decode($request->input('images'),true);

          $work['house_id'] = $this->ship->village_id;
          $id = ClientUserManagerWork::create($work)->id;

          foreach ($images as $image) {
               ClientUserManagerWorksImage::create(['work_id' => $id, 'image' => $image]);
          }

		// 赠送积分
		ClientUserIntegral::create()->data($this->uid,1)->save();
		return json_return($id,'','成功添加工作日志');
	}
	
	// 日志详情
	public function work_detail(BasicRequest $request){
		$id = $request->input('id');
		$data = ClientUserManagerWork::select(DB::raw('client_user_manager_works.*,u.username,u.realname,u.mobile'))->leftJoin('client_user as u','u.id','=','client_user_manager_works.uid')->where(['client_user_manager_works.id'=>$id])->first();
		$images = $data->images()->pluck('image');
		$data->image = $images->first();
		$data->images = $images;
		return json_success('OK',$data);
	}
	//删除日志
     public function work_del(BasicRequest $request){
          $id = $request->input('id');
          $var = ClientUserManagerWork::destroy($id);
          return json_success('OK',$var);
     }
	/**
	 * 获取我的权限
	 */
	public function get_level(BasicRequest $request){
	    $relationship  = ClientUserRoles::select('ship.name', 'ship.cmds')
             ->leftJoin('client_user_relationship as ship',function($query){
                  $query->on('client_user_roles.ship_id','=','ship.id');
             })
             ->where(['client_user_roles.uid' => $this->uid])->first();
	    $cmds = explode(',', $relationship->cmds);
	    
	    $all_cmds = [
	            'company_work_switch',   
                'company_work_rongcloud',
                'company_service_list',
                'company_monitor',
                'company_usercenter_work',
                'company_usercenter_work_detail',
                'company_work_duty_filter',
                'company_work_duty_work',
                'company_work_complaints',
                'company_work_complaints_detail',
                'company_work_complaints_reply',    //差回复总经理信箱
                'company_contacts_index', 'company_contacts_detail', 'company_contacts_message','company_contacts_message_submit',
                'company_contacts_create_client','company_contacts_create_family',	 
            ];
	    //$cmds = $all_cmds;
	    
	    return json_success('OK', ['name' => $relationship->name, 'cmds' => $cmds, 'all_cmds' => $all_cmds]);
	}
}